#include <stdio.h>
#include <string.h>
/*
 author: maxiao
 date: 2023-04-10 17:10
 description: 自定义函数，实现对各种类型数据的排序
*/

// 交换一个字节空间的数据
struct Stu
{
    char id[8];
    char name[12];
    short score;
    short age;
};


void swap(char* a, char* b, int width)
{

    int n = 0;
    while (n<width)
    {
        char tmp = *a;
        *a = *b;
        *b = tmp;
        a++;
        b++;
        n++;
    }
}

int int_cmp(const void* a, const void* b)
{
    if ( (*(int*)a - *(int*)b) > 0 )
        return 1;
    else
        return 0;
}

int cmp_stu_by_name(const void* a, const void* b)
{
    return strcmp( ((struct Stu*)a)->name, ((struct Stu*)b)->name);
}

void bubble_sort(void* base, int size, int width, int(*cmp)(const void*, const void*))
{
    // 控制比较的轮数
    int i = 0;
    int j = 0;
    for (i=0; i<size-1; i++)
    {
        // 控制每轮比较的次数
        for (j=0; j<size-1-i; j++)
        {
            // 判断前后数据的大小
            char* item=(char*)base+j*width;
            if ( cmp(item, item+width) > 0 )
                // 交换数据
                swap(item, item+width, width);
        }
    }
}


void test_int()
{
    int k = 0;
    int arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    int sz = sizeof(arr) / sizeof(arr[0]);
    bubble_sort(arr, sz, sizeof(arr[0]), int_cmp);
    // 输出排序结果
    printf("数组排序后的结果如下所示：\n");
    for (k=0; k<sz; k++)
    {
        printf("%d ", arr[k]);
    }
    printf("\n");
}

void test_struct()
{
    int k = 0;
    struct Stu s[3] = {
        {"10012", "zhangsan", 88, 23},
        {"10009", "wangwu", 91, 24},
        {"10010", "lisi", 95, 22}
    };
    int sz = sizeof(s) / sizeof(s[0]);
    struct Stu* p = s;
    bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name);
    printf("通过姓名对三位同学进行排序，其结果如下所示：\n");
    for (k=0; k<sz; k++)
    {
        printf("id-->%-8s\tname-->%-12s\tscore-->%3d\tage-->%2d\n", p->id, p->name, p->score, p->age);
        p++;
    }
    printf("\n");
}

int main()
{
    test_int();
    printf("========================\n");
    test_struct();
    return 0;
}
